package com.qf.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Description: 公用常量
 * @Data: 2022/9/2 14:55
 * @Pacakge: com.qf.config
 * @ClassName: SpringConfig
 * @Author: fan
 * 配置类
 */
@Configuration//配置类
@ComponentScan(basePackages = "com.qf")//扫描
@PropertySource("classpath:jdbc.properties")//指定properties文件位置
@EnableTransactionManagement//开启事务管理注解
public class SpringConfig {
    @Value("${driverClassName}")
    private String driverClassName;
    @Value("${jdbcUrl}")
    private String jdbcUrl;
    @Value("${user}")
    private String user;
    @Value("${password}")
    private String password;
    @Bean("jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    @Bean("transactionManager")
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean("dataSource")
    public DataSource getDataSource(){
       DataSource dataSource =  new DriverManagerDataSource();
        ((DriverManagerDataSource)dataSource).setDriverClassName(driverClassName);
        ((DriverManagerDataSource)dataSource).setUrl(jdbcUrl);
        ((DriverManagerDataSource)dataSource).setUsername(user);
        ((DriverManagerDataSource)dataSource).setPassword(password);
        return dataSource;
    }
}
